package bubbleindex;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.Callable;

/**
 *
 * @author t
 */
public class UpdateRunnable implements Callable<Integer> {

    private final String Category;
    private final String Selections;
    private final String Sources;
    private final String quandlDataSet;
    private final String quandlDataName;
    private final int quandlColumn;
    private final String isYahooIndex;
    
    /**
     * 
     * @param Category
     * @param Selections
     * @param Sources
     * @param quandlDataSet
     * @param quandlDataName
     * @param quandlColumn
     * @param isYahooIndex 
     */
    public UpdateRunnable (String Category, String Selections, String Sources,
            String quandlDataSet, String quandlDataName, int quandlColumn,
            String isYahooIndex) {
        
        this.Category = Category;
        this.Selections = Selections;
        this.Sources = Sources;
        this.quandlDataSet = quandlDataSet;
        this.quandlDataName = quandlDataName;
        this.quandlColumn = quandlColumn;
        this.isYahooIndex = isYahooIndex;
    }
    
    /**
     * 
     * @return 
     */
    @Override
    public Integer call() {
        if (!BuildIndex.Stop) {
            try {
                URLS selection = new URLS();
                selection.setDataName(Selections);
                if (isYahooIndex.matches("1")) {
                    selection.isSpecial();
                }
                selection.setDataType(Category);
                selection.setSource(Sources);

                if (selection.getSource().matches("QUANDL")) {
                    selection.setQuandlUrl(quandlDataSet, quandlDataName);
                    selection.setQuandlColumn(quandlColumn);
                }

                else if (selection.getSource().matches("FED")) {
                    selection.setFEDUrl();
                }

                else {

                    selection.setYahooUrl();
                }

                ByteArrayOutputStream outputstream = new ByteArrayOutputStream();

                selection.readURL_file(outputstream);
                selection.cleanData(outputstream);

                return 0;

            } catch (UnsupportedEncodingException ex) {
                System.out.println("Unsupported Encoding Exception. Code 020." + ex);
                return 1;
            } catch (FileNotFoundException ex) {
                System.out.println("File Not Found Exception. Code 021." + ex);
                return 1;
            } catch (IOException ex) {
                System.out.println("IO Exception. Code 022." + ex);
                return 1;
            }
        }
        else {
            return 1;
        } 
    }
}
